<script setup lang="ts">
import { Microphone, VideoPause } from "@element-plus/icons-vue";
import { ref, inject, computed, onMounted, onUnmounted } from "vue";
import { useUserStore } from "@/stores";
import { ElMessage } from "element-plus";

const userStore = useUserStore();
const parentSubmitEmitHandler =
  inject<(params: string) => void>("submitEmitHandler");
const senderValue = ref("");
const submitBtnDisabled = ref(false);
function submit(params: string) {
  submitBtnDisabled.value = true;
  if (parentSubmitEmitHandler) {
    parentSubmitEmitHandler(params);
  }
  senderValue.value = "";
}

const senderRef = ref();
let isRecording = ref(false);
const recordingTime = ref(0);
const waveformBars = ref(Array(20).fill(0));
let recordingTimer: number | null = null;
let waveformTimer: number | null = null;

// 语音识别相关
let recognition: any = null;
const recognizedText = ref("");
const isListening = ref(false);
const recognitionError = ref("");

// 检查浏览器是否支持语音识别
const isSpeechRecognitionSupported = ref(false);

// 初始化语音识别
function initSpeechRecognition() {
  if (
    !("webkitSpeechRecognition" in window) &&
    !("SpeechRecognition" in window)
  ) {
    console.warn("浏览器不支持语音识别");
    isSpeechRecognitionSupported.value = false;
    return;
  }

  isSpeechRecognitionSupported.value = true;
  const SpeechRecognition =
    (window as any).webkitSpeechRecognition ||
    (window as any).SpeechRecognition;
  recognition = new SpeechRecognition();

  // 配置语音识别
  recognition.continuous = true; // 连续识别
  recognition.interimResults = true; // 显示中间结果
  recognition.lang = "zh-CN"; // 设置为中文

  // 识别开始
  recognition.onstart = () => {
    console.log("语音识别开始");
    isListening.value = true;
    recognitionError.value = "";
  };

  // 识别结果
  recognition.onresult = (event: any) => {
    let finalTranscript = "";
    let interimTranscript = "";

    for (let i = event.resultIndex; i < event.results.length; i++) {
      const transcript = event.results[i][0].transcript;
      if (event.results[i].isFinal) {
        finalTranscript += transcript;
      } else {
        interimTranscript += transcript;
      }
    }

    // 更新识别的文本
    recognizedText.value = finalTranscript + interimTranscript;
    senderValue.value = recognizedText.value; // 同步到输入框
  };

  // 识别结束
  recognition.onend = () => {
    console.log("语音识别结束");
    isListening.value = false;

    // 如果有识别结果，填充到输入框
    if (recognizedText.value.trim()) {
      senderValue.value = recognizedText.value.trim();
      ElMessage.success("语音识别完成");
    }

    // 语音识别结束时，通知MentionSender并停止录音
    if (isRecording.value && !isStoppingRecording) {
      // 先通知MentionSender停止
      if (senderRef.value?.stopRecognition) {
        senderRef.value.stopRecognition();
      }
      // 然后停止本地录音（会被忽略因为上面的调用会触发onRecordingChange）
    }
  };

  // 识别错误
  recognition.onerror = (event: any) => {
    console.error("语音识别错误:", event.error);
    isListening.value = false;

    switch (event.error) {
      case "network":
        recognitionError.value = "网络错误，请检查网络连接";
        break;
      case "not-allowed":
        recognitionError.value = "请允许麦克风权限";
        break;
      case "no-speech":
        recognitionError.value = "未检测到语音，请重试";
        break;
      default:
        recognitionError.value = "语音识别出错，请重试";
    }

    ElMessage.error(recognitionError.value);

    // 识别错误时，通知MentionSender并停止录音
    if (isRecording.value && !isStoppingRecording) {
      // 先通知MentionSender停止
      if (senderRef.value?.stopRecognition) {
        senderRef.value.stopRecognition();
      }
      // 然后停止本地录音（会被忽略因为上面的调用会触发onRecordingChange）
    }
  };
}

// 开始语音识别
function startSpeechRecognition() {
  if (!recognition || !isSpeechRecognitionSupported.value) {
    ElMessage.warning("浏览器不支持语音识别功能");
    return;
  }

  recognizedText.value = "";
  recognitionError.value = "";

  try {
    recognition.start();
  } catch (error) {
    console.error("启动语音识别失败:", error);
    ElMessage.error("启动语音识别失败");
  }
}

// 停止语音识别
function stopSpeechRecognition() {
  if (recognition && isListening.value) {
    recognition.stop();
  }
}

// 格式化录音时间
const formattedTime = computed(() => {
  const minutes = Math.floor(recordingTime.value / 60);
  const seconds = recordingTime.value % 60;
  return `${minutes.toString().padStart(2, "0")}:${seconds
    .toString()
    .padStart(2, "0")}`;
});

// 生成随机波形数据
function generateWaveform() {
  waveformBars.value = waveformBars.value.map(() => Math.random() * 100 + 10);
}

// 开始录音计时和波形动画
function startRecording() {
  recordingTime.value = 0;
  recordingTimer = setInterval(() => {
    recordingTime.value++;
  }, 1000);

  waveformTimer = setInterval(() => {
    generateWaveform();
  }, 150);

  // 开始语音识别
  startSpeechRecognition();
}

// 内部停止录音标志，防止递归调用
let isStoppingRecording = false;

// 停止录音
function stopRecording() {
  if (isStoppingRecording) return; // 防止递归调用

  isStoppingRecording = true;
  isRecording.value = false;

  if (recordingTimer) {
    clearInterval(recordingTimer);
    recordingTimer = null;
  }
  if (waveformTimer) {
    clearInterval(waveformTimer);
    waveformTimer = null;
  }
  recordingTime.value = 0;
  waveformBars.value = Array(20).fill(0);

  // 停止语音识别
  stopSpeechRecognition();

  // 停止MentionSender的录音状态（需要延迟执行避免递归）
  setTimeout(() => {
    if (senderRef.value?.stopRecognition) {
      senderRef.value.stopRecognition();
    }
    isStoppingRecording = false;
  }, 50);
}

// 监听录音状态变化
function onRecordingChange(flag: boolean) {
  console.log("录音状态变化:", flag);

  // 如果正在执行停止录音，忽略false状态变化以防止递归
  if (isStoppingRecording && !flag) {
    console.log("忽略状态变化，防止递归调用");
    return;
  }

  // 更新录音状态
  isRecording.value = flag;

  if (flag) {
    // 开始录音
    startRecording();
  } else {
    // 停止录音
    if (!isStoppingRecording) {
      stopRecording();
    }
  }
}

// 组件挂载时初始化语音识别
onMounted(() => {
  initSpeechRecognition();
});

onUnmounted(() => {
  // 清理计时器
  if (recordingTimer) {
    clearInterval(recordingTimer);
    recordingTimer = null;
  }
  if (waveformTimer) {
    clearInterval(waveformTimer);
    waveformTimer = null;
  }

  // 停止语音识别
  if (recognition) {
    try {
      if (isListening.value) {
        recognition.stop();
      }
    } catch (error) {
      console.warn("清理语音识别时出错:", error);
    }
    recognition = null;
  }

  // 重置状态
  isListening.value = false;
  isRecording.value = false;
  isStoppingRecording = false;
});

// 启用提交按钮
function enableSubmitBtn() {
  submitBtnDisabled.value = false;
}

// 暴露方法给父组件
defineExpose({
  enableSubmitBtn,
});
</script>

<template>
  <!-- 高级语音录音弹窗 -->
  <el-dialog
    v-model="isRecording"
    width="480px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    class="voice-dialog"
    align-center
  >
    <div class="voice-recording-container">
      <!-- 录音图标和状态 -->
      <div class="recording-header">
        <div class="mic-container">
          <div class="mic-pulse">
            <el-icon class="mic-icon" size="32">
              <Microphone />
            </el-icon>
          </div>
        </div>
        <h3 class="recording-title">
          {{ isListening ? "正在识别语音" : "正在录音" }}
        </h3>
        <p class="recording-subtitle">
          {{ isListening ? "请继续说话，我在听..." : "请清晰地说出您的问题" }}
        </p>
      </div>

      <!-- 语音波形显示 -->
      <div class="waveform-container">
        <div class="waveform">
          <div
            v-for="(height, index) in waveformBars"
            :key="index"
            class="wave-bar"
            :style="{ height: `${height}%` }"
          ></div>
        </div>
      </div>

      <!-- 语音识别结果显示 -->
      <div v-if="recognizedText || recognitionError" class="recognition-result">
        <div v-if="recognizedText" class="recognized-text">
          <p class="text-label">识别结果：</p>
          <p class="text-content">{{ recognizedText }}</p>
        </div>
        <div v-if="recognitionError" class="recognition-error">
          <p>{{ recognitionError }}</p>
        </div>
      </div>

      <!-- 录音时长 -->
      <div class="recording-time">
        <span class="time-display">{{ formattedTime }}</span>
      </div>

      <!-- 操作按钮 -->
      <div class="recording-actions">
        <el-button
          type="danger"
          size="large"
          round
          @click="stopRecording"
          class="stop-button"
        >
          <el-icon><VideoPause /></el-icon>
          停止录音
        </el-button>
      </div>

      <!-- 使用提示 -->
      <div class="recording-tips">
        <p v-if="isSpeechRecognitionSupported">
          💡 说话时保持正常音量，避免环境噪音
        </p>
        <p v-else>⚠️ 浏览器不支持语音识别，请使用Chrome或Edge浏览器</p>
      </div>
    </div>
  </el-dialog>

  <div style="display: flex; flex-direction: column; gap: 20px">
    <MentionSender
      v-model="senderValue"
      variant="updown"
      :disabled="!userStore.isLoggedIn"
      clearable
      allow-speech
      ref="senderRef"
      @recording-change="onRecordingChange"
      :submitBtnDisabled="submitBtnDisabled"
      @submit="submit"
    />
  </div>
</template>

<style scoped lang="scss">
.isSelect {
  color: #626aef;
  border: 1px solid #626aef !important;
  border-radius: 15px;
  padding: 3px 12px;
  font-weight: 700;
}

// 语音弹窗样式
:deep(.voice-dialog) {
  .el-dialog {
    border-radius: 20px;
    overflow: hidden;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;

    .el-dialog__body {
      padding: 0;
    }
  }
}

.voice-recording-container {
  padding: 40px 30px;
  text-align: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  position: relative;
  overflow: hidden;

  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: radial-gradient(
        circle at 20% 50%,
        rgba(255, 255, 255, 0.1) 0%,
        transparent 50%
      ),
      radial-gradient(
        circle at 80% 20%,
        rgba(255, 255, 255, 0.08) 0%,
        transparent 50%
      ),
      radial-gradient(
        circle at 40% 80%,
        rgba(255, 255, 255, 0.06) 0%,
        transparent 50%
      );
  }

  > * {
    position: relative;
    z-index: 1;
  }
}

.recording-header {
  margin-bottom: 32px;
}

.mic-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.mic-pulse {
  position: relative;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  backdrop-filter: blur(10px);
  border: 2px solid rgba(255, 255, 255, 0.3);

  &::before,
  &::after {
    content: "";
    position: absolute;
    border: 2px solid rgba(255, 255, 255, 0.4);
    border-radius: 50%;
    animation: pulse 2s infinite;
  }

  &::before {
    width: 100px;
    height: 100px;
    animation-delay: 0s;
  }

  &::after {
    width: 120px;
    height: 120px;
    animation-delay: 0.5s;
  }

  .mic-icon {
    color: white;
    filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.2));
  }
}

@keyframes pulse {
  0% {
    opacity: 1;
    transform: scale(1);
  }
  100% {
    opacity: 0;
    transform: scale(1.2);
  }
}

.recording-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 8px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.recording-subtitle {
  font-size: 16px;
  margin: 0;
  opacity: 0.9;
  font-weight: 300;
}

.waveform-container {
  margin: 32px 0;
  padding: 20px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 16px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.recognition-result {
  margin: 20px 0;
  padding: 16px;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 12px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.25);
  min-height: 60px;

  .recognized-text {
    .text-label {
      font-size: 14px;
      margin: 0 0 8px 0;
      opacity: 0.8;
      font-weight: 500;
    }

    .text-content {
      font-size: 16px;
      margin: 0;
      line-height: 1.5;
      background: rgba(255, 255, 255, 0.1);
      padding: 12px 16px;
      border-radius: 8px;
      border: 1px solid rgba(255, 255, 255, 0.2);
      word-break: break-all;
      min-height: 20px;
      text-align: left;
    }
  }

  .recognition-error {
    p {
      color: #ff6b6b;
      font-size: 14px;
      margin: 0;
      text-align: center;
      padding: 8px;
      background: rgba(255, 107, 107, 0.2);
      border-radius: 8px;
      border: 1px solid rgba(255, 107, 107, 0.3);
    }
  }
}

.waveform {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 3px;
  height: 80px;
}

.wave-bar {
  width: 4px;
  background: linear-gradient(to top, #ff6b6b, #4ecdc4, #45b7d1);
  border-radius: 2px;
  transition: height 0.15s ease-in-out;
  min-height: 4px;
  box-shadow: 0 0 8px rgba(255, 255, 255, 0.3);

  &:nth-child(odd) {
    background: linear-gradient(to top, #ff9a9e, #fecfef);
  }

  &:nth-child(even) {
    background: linear-gradient(to top, #a8edea, #fed6e3);
  }
}

.recording-time {
  margin: 24px 0;
}

.time-display {
  font-size: 28px;
  font-weight: 300;
  font-family: "Monaco", "Menlo", "Courier New", monospace;
  background: rgba(255, 255, 255, 0.15);
  padding: 12px 24px;
  border-radius: 50px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.recording-actions {
  margin: 32px 0 24px 0;
}

.stop-button {
  padding: 14px 32px;
  font-size: 16px;
  font-weight: 500;
  background: rgba(255, 69, 58, 0.9) !important;
  border: none !important;
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 25px rgba(255, 69, 58, 0.3);
  transition: all 0.3s ease;

  &:hover {
    background: rgba(255, 69, 58, 1) !important;
    transform: translateY(-2px);
    box-shadow: 0 12px 35px rgba(255, 69, 58, 0.4);
  }

  &:active {
    transform: translateY(0);
  }

  .el-icon {
    margin-right: 8px;
  }
}

.recording-tips {
  margin-top: 20px;

  p {
    font-size: 14px;
    margin: 0;
    opacity: 0.8;
    background: rgba(255, 255, 255, 0.1);
    padding: 12px 20px;
    border-radius: 12px;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.15);
  }
}

// 弹窗进入动画
:deep(.el-dialog__wrapper) {
  .el-dialog {
    animation: dialogSlideIn 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
  }
}

@keyframes dialogSlideIn {
  from {
    opacity: 0;
    transform: scale(0.8) translateY(-50px);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

// 响应式设计
@media (max-width: 768px) {
  :deep(.voice-dialog .el-dialog) {
    width: 90% !important;
    margin: 0;
  }

  .voice-recording-container {
    padding: 30px 20px;
  }

  .mic-pulse {
    width: 60px;
    height: 60px;

    &::before {
      width: 80px;
      height: 80px;
    }

    &::after {
      width: 100px;
      height: 100px;
    }
  }

  .recording-title {
    font-size: 20px;
  }

  .time-display {
    font-size: 24px;
    padding: 10px 20px;
  }

  .waveform {
    height: 60px;
  }
}
</style>
